import 'dart:async';
import 'package:flame/components.dart';
import 'package:flame/events.dart';
import 'package:flame/flame.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flutter/material.dart';
import 'package:freedom/const/app_content.dart';
import 'package:freedom/page/mahjong/bloc/room_bloc.dart';
import 'package:freedom/page/mahjong/bloc/room_bloc_state.dart';
import 'package:freedom/page/mahjong/common/common_card.dart';
import 'package:freedom/page/mahjong/keneck/menu_dialog_component.dart';
import 'package:freedom/util/customer_dialog.dart';
import 'package:freedom/util/permission.dart';
import 'package:freedom/webrtc/mircophone_open.dart';
import 'package:permission_handler/permission_handler.dart';
import '../common/mahjong_context.dart';
import '../mahjong_game.dart';

class MahjongMenuComponent extends PositionComponent
    with HasGameRef<MahjongIndexGame> {
  var microphoneImage = Flame.images.fromCache('mahjong/util/microphone.png');

  MahjongMenuComponent()
      : super(
            size: MahjongContext().menuSize,
            position: MahjongContext().menuPosition);

  @override
  FutureOr<void> onLoad() {
    //MircoPhoneOpen().init();
    //debugMode = true;
    add(MahjongUtilItem(
        imageSrc: 'mahjong/util/menu.png',
        size: Vector2(size.x, size.x),
        code: "openMessage",
        position: Vector2(0, MahjongContext().marginTop),
        itemOnTap: (selected) {
          CustomerDialog.showGamingDialog((cancel) => MenuDialogWidget(),
              groupKey: CustomerDialog.GAME_MENU_GROUP);
        }));

    // 添加麦克风
    add(MahjongUtilItem(
        imageSrc: 'mahjong/util/micro_close.png',
        size: Vector2(size.x, size.x),
        code: "openMicrophone",
        switchImageSrc: 'mahjong/util/microphone.png',
        position: Vector2(
            0, MahjongContext().bottomHandCardAreaPoint.y - size.x * 4.1),
        itemOnTap: (selected) {
          if (selected) {
            PermissionUtil.requestPermission([
              PerEnt(Permission.microphone, "未授权麦克风,无法开启"),
            ], (res) {
              if (res.status) {
                MircoPhoneOpen().openLocalMirco();
              }
            });
          } else {
            MircoPhoneOpen().closeLocalMirco();
          }
        }));
    add(MahjongUtilItem(
        imageSrc: 'mahjong/util/message.png',
        size: Vector2(size.x, size.x),
        code: "openMessage",
        position: Vector2(
            0, MahjongContext().bottomHandCardAreaPoint.y - size.x * 2.8),
        itemOnTap: (selected) {
          MahjongContext().showOverlay(SystemOverlay.messageInfoDialog);
        }));
    MahjongUtilItem tipsComUtil = MahjongUtilItem(
        imageSrc: 'mahjong/commons/tips.png',
        size: Vector2(size.x, size.x),
        code: "openTips",
        position: Vector2(
            0, MahjongContext().bottomHandCardAreaPoint.y - size.x * 1.5),
        itemOnTap: (selected) {
          // 取出用户所有的手牌
          List<int> userHandCards = [];
          int? selectCard;
          game.bottomCardArea?.children.forEach((element) {
            if (element is CommonCard && element.handCard) {
              if (element.selected) {
                selectCard = element.cardCode;
              }
              userHandCards.add(element.cardCode);
            }
          });
          if (userHandCards.length % 3 == 2 && selectCard != null) {
            userHandCards.remove(selectCard);
          }
          MahjongContext()
              .reInitHuCardTips(selected, userAllCards: userHandCards);
        });
    add(tipsComUtil);
    add(
      FlameBlocListener<RoomBloc, RoomBlocState>(
        onNewState: (RoomBlocState state) {
          tipsComUtil.selected = state.showTips;
        },
      ),
    );
    return super.onLoad();
  }
}

class MahjongUtilItem extends PositionComponent with TapCallbacks {
  String imageSrc;
  String code;
  String? switchImageSrc;
  Function? itemOnTap;

  var mainImage;
  var switchImage;

  SpriteComponent? icon;

  bool selected = false;

  MahjongUtilItem(
      {required Vector2 size,
      required Vector2 position,
      required this.imageSrc,
      required this.code,
      this.switchImageSrc,
      this.itemOnTap})
      : super(size: size, position: position);

  @override
  bool containsLocalPoint(Vector2 point) {
    final rect = Rect.fromLTWH(0, 0, width, height);
    return rect.contains(Offset(point.x, point.y));
  }

  @override
  void onTapDown(TapDownEvent event) {
    super.onTapDown(event);
    selected = !selected;
    var currentImage = mainImage;
    if (selected && switchImageSrc != null) {
      currentImage = switchImage;
    }
    remove(icon!);
    icon = SpriteComponent(
        sprite: Sprite(currentImage),
        size: Vector2(size.x * 2 / 3, size.x * 2 / 3),
        position: Vector2(size.x / 6, size.x / 6));
    add(icon!);
    if (itemOnTap != null) {
      itemOnTap!(selected);
    }
  }

  @override
  FutureOr<void> onLoad() {
    mainImage = Flame.images.fromCache(imageSrc);
    if (switchImageSrc != null) {
      switchImage = Flame.images.fromCache(switchImageSrc!);
    }
    add(CircleComponent(
        radius: size.x / 2,
        position: Vector2(0, 0),
        paint: Paint()..color = const Color(0x35A9A9A9)));
    icon = SpriteComponent(
        sprite: Sprite(mainImage),
        size: Vector2(size.x * 2 / 3, size.x * 2 / 3),
        position: Vector2(size.x / 6, size.x / 6));
    add(icon!);
    return super.onLoad();
  }

  @override
  void render(Canvas canvas) {
    super.render(canvas);
    /*  if (selected) {
      final Paint paint = Paint()
        ..color = Color.fromARGB(110, 136, 136, 136)
        ..style = PaintingStyle.fill
        ..strokeWidth = 1.0;
      RRect rect =
          RRect.fromLTRBR(size.x, size.y, 0, 0, const Radius.circular(0));
      canvas.drawRRect(rect, paint);
    } */
  }
}
